/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import data.Data;

/**
 *
 * @author Riso-Desktop
 */
@WebServlet(name = "servlet", urlPatterns = {"/servlet"})
public class servlet extends HttpServlet {

    HttpSession session;
    Data data;
    String driver = "com.mysql.jdbc.Driver";
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    int id = 0;
    PrintWriter out;
    Integer id_usera = 0;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    public void init() {
        pripojenie();
    }

    public void pripojenie() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + "portalpredeti", "root", "");
            stmt = con.createStatement();
        } catch (Exception ex) {
        }
    }

    public int over(String meno, String heslo) {
        int vysledok = 0;
        try {
            stmt = con.createStatement();
            rs = stmt.executeQuery("select min(ID) as iid,count(ID) as pocet from user where Meno='"
                    + meno + "' and Heslo='" + heslo + "'");

            rs.next();
            if (rs.getInt("pocet") == 1) {
                vysledok = rs.getInt("iid");
            }
        } catch (Exception ex) {
            return 0;
        }
        return vysledok;

    }

    public void ZobrazNeopravnenyPristup(HttpServletResponse response) {
        out = null;
        try {
            out = response.getWriter();
            out.println("Neoprávnený prístup");
        } catch (Exception ex) {
            out.println(ex.toString());
        } finally {
            out.close();
        }
    }

    public void ZapamatajUdajeOUserovi(int id_usera) {
        // nacitam potrebne udaje z databazy
        try {
            stmt = con.createStatement();
            rs = stmt.executeQuery("select meno from user where id='" + id_usera + "'");
            rs.next();
            session.setAttribute("ID", (Integer) id_usera);
            session.setAttribute("meno", rs.getString("meno"));
            session.setMaxInactiveInterval(300); // 5 minut

        } catch (Exception ex) {
            out.println(ex.toString());
        }
    }

    private void ponukaAppletov() {
        //načítanie stránky s ponukou
        out.println("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
                + "<html xmlns='http://www.w3.org/1999/xhtml'>"
                + "<head>"
                + "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
                + "<title>The SimpsonsMath</title>"
                + "</head>"
                + "<body style='background-image:url(lib/bart.png);background-repeat:no-repeat;background-position:center'>"
                + "<div align='center' style='height:600px'>"
                + "  <p>&nbsp;</p>"
                + "  <p>&nbsp;</p>"
                + "  <p>&nbsp;</p>"
                + "<div style='width:299px;height:316px;background-image:url(lib/ponuka_pozadie.png);background-repeat:no-repeat;background-position:center'>"
                + "  <h2>Ahoj "+session.getAttribute("meno") +"</h2>"
                + "  <p>&nbsp;</p>"
                + "<p style='font-size:18px'>Môžeš sa preskúšať v týchto úlohách: </p>"
                + "  <p>"
                + "    <a style='color:#000' href='applet2.jsp'>Príklady na sčítavanie a odčítavanie</a><br />"
                + "    <a style='color:#000' href='applet3.jsp'>Doplňovačky na sčítavanie a odčítavanie</a><br />"
                + "    <a style='color:#000' href='applet4.jsp'>Slovné úlohy</a><br />"
                + "    <a style='color:#000' href='applet5.jsp'>Reťazovka</a><br />"
                + "  </p>"
                + "  <p>"
                + "  Zahrať hru na odreagovanie:<br />"
                + " <a style='color:#000' href='applet.jsp'>Priraď mláďatá k rodičom</a>"
                + " </p>"
                + " <p>Alebo si pozrieť svoje skóre:<br /> <a style='color:#000' href='skore'>Skóre</a></p>"
                + " <a style='color:#000' href='odhlas'>Odhlásiť</a>"
                + "</div>"
                + "</div>"
                + "</body>");

    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
//        response.setContentType("application/x-java-serialized-object");
        response.setContentType("text/html;charset=UTF-8");
        session = request.getSession();
        try {
//            data = citaj(request);
//            posli(response);
            out = response.getWriter();
            try {
                session = request.getSession();
                id_usera = (Integer) session.getAttribute("ID");
                if (id_usera == null) {
                    if (request.getContentType() == null) {
                        ZobrazNeopravnenyPristup(response);
                        return;
                    }
                    String tlacidlo = (request.getParameter("tlacidlo")).substring(0, 1);

                    if (tlacidlo.equals("P")) {
                        id_usera = over(request.getParameter("Login"), request.getParameter("Heslo"));
                        if (id_usera == 0) {
                            ZobrazNeopravnenyPristup(response);
                            return;
                        }
                        ZapamatajUdajeOUserovi(id_usera);
                        ponukaAppletov();
                    }
                }else{
                    ponukaAppletov();
                }
            } catch (Exception e) {
                out.println(e.toString());
            } finally {
                out.close();
            }


        } catch (Exception e) {
        } finally {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
